 ///
 /// @file    Derived.cc
 /// @author  lemon(haohb13@gmail.com)
 /// @date    2023-05-02 16:22:46
 ///
 
#include <iostream>
using std::cout;
using std::endl;

class Base{
public:
	Base(int ibase = 0)
	: _ibase(ibase)
	{	cout << "Base(int=0)" << endl;	}
	
	void print() const
	{	cout << "Base::_ibase = " << _ibase << endl;	}

private:
	long _ibase;
};

class Derived
: public Base
{
public:
	Derived(int ibase, int derived)
	: Base(ibase) //显式调用基类的构造函数，是可以防止出现错误
	, _iderived(0)
	{	cout << "Derived()" << endl;	}
	
	void display() const 
	{
		cout << "Derived::_iderived = " << _iderived << endl;
	}

private:
	long _iderived;
};
 
void test0() 
{
	Base base(2);
	Base * pbase = &base;
	pbase->print();
	//Base & ref1 = base;

	Derived d(1, 10);
	d.display();

	Derived * pderieved = &d;
	pderieved->display();
	cout << endl;

	pbase = &d;//ok 基类指针指向了派生类对象
	pbase->print();//该操作是合法的，不需要强制转换

	cout << endl;
	pderieved = &base;//error, 派生类指针指向了基类对象
	pderieved->display();//强制转换之后，是不安全的

	Base & ref1 = d;//ok 基类引用可以绑定到派生类对象
	ref1.print();

	//Derived & ref2 = base;//error 派生类引用不能绑定到基类对象

	//如果该操作能够执行成功，这意味着初始化形参
	//const Derived & rhs = base  这是不合法的
	//Derived & operator=(const Derived & rhs);
	//d = base;//error 将一个基类对象赋值给派生类对象
	//d.operator=(base);
	
	//初始化形参  const Base & rhs = d;
	//Base & operator=(const Base & rhs);
	base.operator=(d);
	base = d;//用派生类对赋值给基类对象
} 
 
int main(void)
{
	test0();
	return 0;
}















